import os
from datetime import datetime

from django.conf import settings
from django.http import JsonResponse
from django.views.decorators.http import require_GET
from django.views.decorators.http import require_POST

from apps.base.models import User, Department
from service import res_json_data
from service import ret
from .forms import UserAddForm, UserEditForm, ResetPwdForm, UserInfoForm
from service.encrypt import md5


# /api/v1/user/department_get/
@require_GET
def user_department_get(request):
    def get_children(item):
        """递归获取子部门"""
        children = []
        for child in item.department_set.filter(is_deleted=False):
            child_data = child.json_department_tree()
            child_data['children'] = get_children(child)
            children.append(child_data)
        return children

    first_queryset = Department.objects.filter(pid__isnull=True, is_deleted=False)

    res_data = []
    for item in first_queryset:
        item_data = item.json_department_tree()
        item_data['children'] = get_children(item)
        res_data.append(item_data)

    return res_json_data.tree_api(data=res_data, select=[])


# /api/v1/user/table/  > 用户列表数据+分页+筛选
@require_GET
def get_list_as_table(request):
    # http://127.0.0.1:8000/api/v1/user/table/?page=1&limit=10
    # &nickname=dc&postion=CEO&gender=1&is_enabled=1&start_time=2024-11-1&end_time=2024-12-18&department_ids=3%2C4%2C7%2C5%2C1

    # print(request.GET)
    # 过滤条件
    nickname = request.GET.get('nickname')
    postion = request.GET.get('postion')
    gender = request.GET.get('gender')
    is_enabled = request.GET.get('is_enabled')
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    department_ids = request.GET.get('department_ids')  # '3,4,7,5,1'
    # 分页
    page = request.GET.get('page', 1)  # 第几页
    limit = request.GET.get('limit', 10)  # 每页显示多少条

    queryset = User.objects.filter(is_deleted=False)
    if nickname:
        queryset = queryset.filter(nickname__icontains=nickname)
    if postion:
        queryset = queryset.filter(postion__icontains=postion)
    if gender:
        queryset = queryset.filter(gender=int(gender))
    if is_enabled:
        queryset = queryset.filter(is_enabled=int(is_enabled))
    if start_time and end_time:
        queryset = queryset.filter(create_datetime__gte=start_time, create_datetime__lte=end_time)
    if department_ids:
        department_ids_list = department_ids.split(',')
        queryset = queryset.filter(department_id__in=department_ids_list)

    queryset_page = queryset[(int(page) - 1) * int(limit): int(page) * int(limit)]
    res_data = []
    for item in queryset_page:
        item_data = item.json()
        res_data.append(item_data)

    return res_json_data.table_api(data=res_data, count=len(queryset))


# /api/v1/user/avatar/
@require_POST
def user_avatar(request):
    """用于用户头像上传"""
    user_id = request.POST.get('id')
    a_type = request.POST.get('type')  # 有三个可能值: 'add', 'edit', 'info'
    # 个人中心的用户只能修改自己的头像!!
    if a_type == 'info' and int(user_id) != request.auth:
        return res_json_data.illegal_api(msg="非法操作!")

    upload_object = request.FILES.get("file")
    if upload_object.size > 1024 * 500:
        return JsonResponse({
            "code": ret.UPLOAD_OVERSIZE,
            "msg": "请上传小于500kb的图片!"
        })

    if a_type == "add":
        file_name = '0' + "." + upload_object.content_type.split('/')[1]  # '0.png'  你还不知道这图片是哪个用户的!
    else:
        file_name = str(request.POST.get('id')) + "." + upload_object.content_type.split('/')[1]  # '1.png' 指定用户的头像

    upload_url = os.path.join(settings.UPLOAD_PATH, file_name)  # 'upload/1.png'
    media_path = os.path.join(settings.MEDIA_URL, upload_url)  # '/media/upload/1.png'
    save_path = os.path.join(settings.MEDIA_ROOT, upload_url)  # "/Users/dengchuan/Desktop/pear_admin_django/media/upload/1.png"
    asb_url = request.build_absolute_uri(media_path)  # http://127.0.0.1:8000/media/upload/1.png

    # 获取目录路径
    directory = os.path.dirname(save_path)
    # 创建目录（如果不存在）
    if not os.path.exists(directory):
        os.makedirs(directory)
    # 保存图片
    with open(save_path, 'wb') as destination:
        for chunk in upload_object.chunks():
            destination.write(chunk)

    # 若添加这几行代码,那么修改时,上传图片成功,则被修改用户的头像的更新即可生效!(刷新就看得到
    # if a_type == "edit":
    #     # 更新用户头像在db中的值
    #     user_obj = User.objects.filter(id=request.POST.get('id'), is_deleted=False).first()
    #     user_obj.avatar = media_path
    #     user_obj.save()

    context = {
        "code": ret.SUCCESS,
        "msg": "上传成功!",
        "data": {
            'media_path': media_path,  # 头像字段在数据库中存储的值!
            'abs_url': asb_url,  # 图片在后端服务器访问的路径
        }
    }
    return JsonResponse(context)


# /api/v1/user/get_dep_select/
@require_GET
def get_dep_select(request):
    dep_info_list = []
    dep_queryset = Department.objects.filter(is_deleted=False)
    for dep_obj in dep_queryset:
        dep_info_list.append(dep_obj.json_tree())  # layui第三方组件combotree拿到该数据后会自动构建树!
    return JsonResponse(dep_info_list, safe=False)


# /api/v1/user/add/
@require_POST
def user_add(request):
    # print(request.POST)
    form = UserAddForm(request.POST)
    if not form.is_valid():
        return res_json_data.no_valid_api(form)
    if not request.POST.get('avatar'):
        form.instance.avatar = settings.DEFAULT_AVATAR  # 默认头像
        # print(form.instance.__dict__)
        form.save()  # 用户没有选择上传头像, 则默认使用默认头像
        return res_json_data.success_api(msg='用户新增成功!')

    user_obj = form.save()
    # 注: 当 os.path.join() 的第二个或后续参数是一个以 / 开头的路径时,它会被视为绝对路径,从而忽略前面的所有参数
    old_path = os.path.join(settings.BASE_DIR, user_obj.avatar.lstrip('/'))
    new_path = os.path.dirname(old_path) + '/' + str(user_obj.id) + "." + user_obj.avatar.split(".")[-1]
    os.rename(old_path, new_path)
    new_media_path = new_path.replace(str(settings.BASE_DIR), "", 1)
    user_obj.avatar = new_media_path
    user_obj.save()
    return res_json_data.success_api(msg='用户新增成功!')


# /api/v1/user/edit/
@require_POST
def user_edit(request):
    # print(request.POST)
    edit_id = request.POST.get('id')
    user_obj = User.objects.filter(id=edit_id, is_deleted=False).first()
    if not user_obj:
        return res_json_data.not_found_api(msg="用户不存在或已删除!")

    form = UserEditForm(request.POST, instance=user_obj)
    if not form.is_valid():
        return res_json_data.no_valid_api(form)

    # 手机号和邮箱不能重复 除了自身
    mobile = form.cleaned_data.get('mobile')
    email = form.cleaned_data.get('email')
    if User.objects.exclude(id=edit_id).filter(mobile=mobile, is_deleted=False).exists():
        return res_json_data.summary_error_api(msg="手机号已存在!")
    if User.objects.exclude(id=edit_id).filter(email=email, is_deleted=False).exists():
        return res_json_data.summary_error_api(msg="邮箱已存在!")

    form.save()
    return res_json_data.success_api(msg='用户修改成功!')


# /api/v1/user/del/
@require_POST
def user_del(request):
    del_id = request.POST.get('id')
    user_obj = User.objects.filter(id=del_id, is_deleted=False).first()
    if not user_obj:
        return res_json_data.not_found_api(msg="用户不存在或已删除!")

    user_obj.is_deleted = True  # 标记为删除
    user_obj.save()
    return res_json_data.success_api(msg='用户删除成功!')


# /api/v1/user/is_enabled/
@require_POST
def user_is_enabled(request):
    enabled_id = request.POST.get('id')
    is_enabled = request.POST.get('is_enabled')
    user_obj = User.objects.filter(id=enabled_id, is_deleted=False).first()
    current_user_name = str(user_obj.nickname)
    if not user_obj:
        return res_json_data.not_found_api(msg=f"{current_user_name}-该用户不存在或已删除!")

    # 禁用以及启用
    user_obj.is_enabled = is_enabled
    user_obj.save()
    msg = '用户启用成功!' if int(is_enabled) else '用户禁用成功!'
    return res_json_data.success_api(msg=msg)


# /api/v1/user/reset_pwd/
@require_POST
def user_reset_pwd(request):
    # print(request.POST)
    reset_pwd_user_id = request.POST.get('user_id')
    # print(reset_pwd_user_id)
    user_obj = User.objects.filter(id=reset_pwd_user_id, is_deleted=False).first()
    if not user_obj:
        return res_json_data.not_found_api(msg=f"该用户不存在或已删除!")

    form = ResetPwdForm(request.POST, instance=user_obj)
    if not form.is_valid():
        return res_json_data.no_valid_api(form)
    form.save()
    return res_json_data.success_api(msg='密码重置成功!')


# /api/v1/user/power_update/
@require_POST
def user_role_update(request):
    """给用户授权"""
    # print(request.POST)
    choose_roles = request.POST.get("choose_roles")
    user_id = request.POST.get("user_id")
    user_obj = User.objects.filter(id=user_id, is_deleted=False).first()
    if not user_obj:
        return res_json_data.not_found_api(msg="授角的用户不存在或已删除!")
    # print(choose_roles, user_id)
    if not choose_roles:
        user_obj.role_list.clear()
    else:
        # 先清空再重新添加
        role_id_list = choose_roles.split(",")
        user_obj.role_list.clear()
        user_obj.role_list.add(*role_id_list)
    return res_json_data.success_api(msg="用户授角成功!")


# /api/v1/user/info/  -- 个人中心,基本信息的修改
@require_POST
def user_info(request):
    edit_id = request.POST.get('id')
    if int(edit_id) != request.auth:
        return res_json_data.illegal_api(msg="非法操作!")
    user_obj = User.objects.filter(id=edit_id, is_deleted=False).first()
    if not user_obj:
        return res_json_data.not_found_api(msg="用户不存在或已删除!")

    form = UserInfoForm(request.POST, instance=user_obj)
    if not form.is_valid():
        return res_json_data.no_valid_api(form)

    # 邮箱不能重复除了自身
    email = form.cleaned_data.get('email')
    if User.objects.exclude(id=edit_id).filter(email=email, is_deleted=False).exists():
        return res_json_data.summary_error_api(msg="邮箱已存在!")

    form.save()
    return res_json_data.success_api(msg='修改信息成功!')


# /api/v1/user/iphone/  -- 个人中心,手机号的修改
def user_iphone(request):
    edit_id = request.POST.get('id')
    if int(edit_id) != request.auth:
        return res_json_data.illegal_api(msg="非法操作!")
    user_obj = User.objects.filter(id=edit_id, is_deleted=False).first()
    if not user_obj:
        return res_json_data.not_found_api(msg="用户不存在或已删除!")

    old_mobile = request.POST.get('old_mobile')
    if not User.objects.filter(id=edit_id, mobile=old_mobile, is_deleted=False).exists():
        return res_json_data.summary_error_api(msg="原手机号不正确!")
    # Todo: 短信验证码验证,此处暂且直接修改啦!
    new_mobile = request.POST.get('new_mobile')
    user_obj.mobile = new_mobile
    user_obj.save()
    return res_json_data.success_api(msg='修改手机号成功!')


# /api/v1/user/iphone/  -- 个人中心,密码的修改
def user_pwd(request):
    # print(request.POST)
    edit_id = request.POST.get('id')
    if int(edit_id) != request.auth:
        return res_json_data.illegal_api(msg="非法操作!")
    user_obj = User.objects.filter(id=edit_id, is_deleted=False).first()
    if not user_obj:
        return res_json_data.not_found_api(msg="用户不存在或已删除!")

    old_pwd = request.POST.get('old_pwd')
    new_pwd = request.POST.get('new_pwd')
    re_pwd = request.POST.get('re_pwd')
    if not User.objects.filter(id=edit_id, password_hash=md5(old_pwd)).exists():
        return res_json_data.summary_error_api(msg="原密码不正确!")

    if new_pwd != re_pwd:
        return res_json_data.summary_error_api(msg="两次密码输入不一致!")

    user_obj.password_hash = md5(new_pwd)
    user_obj.save()
    return res_json_data.success_api(msg='修改密码成功!')
